import 'dart:async';
import 'dart:io';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

import '../utils/internet_connection_checker_plus/internet_connection_checker_plus.dart';
import '../widgets/common/jzx_toast.dart';

/// `event_bus`通知挂载
class AppNeedToLogin {}

/// `event_bus`通知挂载
/// 过滤/加入操作用户，用于刷新视频/帖子/关注用户
class RefreshBlockUsers {}

class RefreshFollowUsers {}

/// 完成任务首页显示成功的alert
class FulfilTask {
  final int level;

  FulfilTask(this.level);
}

class RefreshPostLike {}

class JzxAppService extends GetxService {
  static JzxAppService get to => Get.find();

  /// 全局通知
  static EventBus get bus => to._bus;
  var _bus = EventBus();

  /// 获取设备的唯一编码
  SystemDevice device = SystemDevice();

  PackageInfo? packageInfo;

  /// 网络连接状态
  StreamSubscription<InternetConnectionStatus>? _subscription;

  /// 是否建立网络连接
  Timer? _trackTimer;

  /// 文件路径
  late Directory fileDirectory;

  @override
  void onInit() async {
    super.onInit();

    initDeviceInfo();
    initConnectivity();
    packageInfo = await PackageInfo.fromPlatform();

    _trackTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      // 在这里执行你想要的任务
      attTracking();
    });

    fileDirectory = await getApplicationDocumentsDirectory();
  }

  rest() {
    bus.destroy();
    _bus = EventBus();
  }

  /// 获取文件路径
  String filePath(String fileName) {
    final filePath = fileDirectory.path;
    return "$filePath/$fileName";
  }

  void attTracking() async {
    final TrackingStatus status =
        await AppTrackingTransparency.trackingAuthorizationStatus;
    if (status == TrackingStatus.notDetermined) {
      Future.delayed(const Duration(seconds: 2), () async {
        await AppTrackingTransparency.requestTrackingAuthorization();
      });
    } else {
      // 释放定时器
      _trackTimer?.cancel();
      _trackTimer = null;
    }
  }

  /// 网络连接
  initConnectivity() async {
    _subscription = InternetConnectionCheckerPlus.createInstance(
      checkInterval: const Duration(seconds: 10),
    ).onStatusChange.listen((status) {
      switch (status) {
        case InternetConnectionStatus.disconnected:
          showMessage('No Internet connection');
          break;
        case InternetConnectionStatus.connected:
          BotToast.closeAllLoading();
          break;
      }
    });
  }

  /// 初始化设备信息
  initDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

    if (GetPlatform.isAndroid) {
      AndroidDeviceInfo info = await deviceInfo.androidInfo;
      device = device.copyWith(
        name: info.model,
        identifier: info.id,
        systemVersion: '${info.version.sdkInt}',
        model: info.model,
      );
    } else if (GetPlatform.isIOS) {
      IosDeviceInfo info = await deviceInfo.iosInfo;
      device = device.copyWith(
        name: info.name,
        identifier: info.identifierForVendor ?? 'ios_device',
        systemVersion: info.systemVersion,
        model: info.model,
      );
    }

    // print(device.toString());
  }

  static Future clipboard(String data, {String tips = 'Successfully copied'}) {
    return Clipboard.setData(ClipboardData(text: data)).then((value) {
      showMessage(tips);
    });
  }

  @override
  void onClose() {
    _subscription?.cancel();
    super.onClose();
  }
}

/// 系统设备信息
class SystemDevice {
  /// 设备名称
  final String name;

  /// 系统版本
  final String systemVersion;

  /// 唯一标识
  final String identifier;

  /// 设备型号
  final String model;

  SystemDevice({
    this.name = '',
    this.systemVersion = '',
    this.identifier = '',
    this.model = '',
  });

  SystemDevice copyWith({
    String? name,
    String? systemVersion,
    String? identifier,
    String? model,
  }) {
    return SystemDevice(
      name: name ?? this.name,
      systemVersion: systemVersion ?? this.systemVersion,
      identifier: identifier ?? this.identifier,
    );
  }

  @override
  String toString() =>
      'SystemDevice(name: $name, systemVersion: $systemVersion, identifier: $identifier)';
}
